🔁 Top 10 Python Dictionary Methods You Must Know

 

🔁 Top 10 Python Dictionary Methods You Must Know 🧠📘

1. get() – Safely retrieve value by key

d.get('a') # Returns value if key exists, otherwise None

2. keys() – Get all keys

d.keys() # Returns dict_keys(['a', 'b'])

3. values() – Get all values

d.values() # Returns dict_values([1, 2])

4. items() – Get key-value pairs

d.items() # Returns dict_items([('a', 1), ('b', 2)])

5. update() – Merge another dictionary

d.update({'c': 3}) # Adds/updates keys: {'a':1, 'b':2, 'c':3}

6. pop() – Remove item by key

d.pop('a') # Returns value and removes key 'a'

7. popitem() – Remove last inserted item

d.popitem() # Returns (key, value) of last item

8. setdefault() – Get value or set default

d.setdefault('x', 0) # Returns value or inserts 'x':0 if missing

9. clear() – Remove all items

d.clear() # Results in empty dictionary {}

10. copy() – Create a shallow copy

new_d = d.copy() # Copies dictionary without affecting original

Comments

Popular posts from this blog

🔁 Top 30 Python List Methods You Should Know

Python Project 7: Read & Write JSON Files

✅ Python – Quick Start Guide for Beginners